package com.wx.gof.pattern.structural.proxy.dynamicproxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @ClassName JayCglibProxy
 * @Author wx
 * @Description 周杰伦动态代理-接口方式-cglib动态代理
 * @Date 2018-12-12-20:39
 */
public class JayCglibProxy implements MethodInterceptor {
    /**
     * 目标对象-被代理对象
     */
    private Object target;
    /**
     * 创建加强器，用来创建动态代理类
     */
    private Enhancer enhancer=new Enhancer();

    public JayCglibProxy(Object target) {
        this.target = target;
    }


    public Object bind() {
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();

    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        String methodName = method.getName();
        switch (methodName) {
            case "sign":
                //环绕处理
                aroundAdvice();
                return null;
            case "work":
                //前置处理
                beforeMethod();
                methodProxy.invokeSuper(o, objects);
                //后置处理
                afterMethod();
                return null;
            case "sing":
                // 获取当前方法传入参数
                Class<?>[] methodParameterTypes = method.getParameterTypes();
                System.out.print("我会唱:");
                for (int i = 0; i < methodParameterTypes.length; i++) {
                    System.out.println(objects[i] + ",");
                }
                System.out.println("粉丝狂欢");
                methodProxy.invokeSuper(o, objects);
                return null;
            default:
                return methodProxy.invokeSuper(o, objects);
        }
    }


    /**
     * @param
     * @methodName: aroundAdvice
     * @author: wx
     * @description: 坏绕通知
     * @date: 2018/12/12
     * @return: void
     */
    private void aroundAdvice() {
        System.out.println("方文山代替周杰伦签约合同");
    }

    /**
     * @param
     * @methodName: beforeMethod
     * @author: wx
     * @description: 前置通知-前置增强
     * @date: 2018/12/12
     * @return: void
     */
    private void beforeMethod() {
        System.out.println("调整状态");
    }

    /**
     * @param
     * @methodName: afterMethod
     * @author: wx
     * @description: 后置通知
     * @date: 2018/12/12
     * @return: void
     */
    private void afterMethod() {
        System.out.println("休息一会");
    }

}
